package com.vans.practice.define_classloader;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 模拟热部署
 * @Author elle
 * @Date 2020/9/15 16:13
 * @Description:
 */
public class MyTest {

    public static void main(String[] args) {
        System.out.println("调用老版本的MyGirl类");
        try {
            loadClass();
            System.gc();
            //替换加载的class文件
            File oldFile = new File("X:\\java_workspace\\vans\\vans-practice\\target\\classes\\com\\vans\\practice\\service\\MyGirl.class");
            File newFile = new File("X:\\java_test\\test_class_load\\MyGirl.class");
            oldFile.delete();
            boolean succ = newFile.renameTo(oldFile);
            if (!succ) {
                System.out.println("热部署失败!");
            }
            else {
                System.out.println("调用新版本的MyGirl类");
                loadClass();
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    // 通过反射机制创建对象
    public static void loadClass() throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
        MyClassLoader myLoader = new MyClassLoader();
        Class<?> class1 = myLoader.findClass("com.vans.practice.defineClassLoader.MyGirl");
        //通过类class的构造方法创建实例
        Object obj1 = class1.getDeclaredConstructor().newInstance();
        Method method = class1.getMethod("intro");
        method.invoke(obj1);
//        System.out.println(obj1.getClass());
//        System.out.println(obj1.getClass().getClassLoader());
    }
}
